package com.lsa.letcode.the142.linkedListCycleII;

import static org.junit.Assert.*;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

import com.lsa.helpers.Utils;
import com.lsa.letcode.common.LetCodeTestBase;
import com.lsa.letcode.common.ListNode;

public class LinkedListCycleTest extends LetCodeTestBase {
	@Test
	public void test() throws Exception {
		Solution s = new Solution();
		assertEquals(1, s.detectCycle(encycle(asList(1,2,3))).val);
		assertEquals(5, s.detectCycle(encycle(asList(Utils.createIntArray1D(1, 11, 1)), 5)).val);
		assertEquals(51, s.detectCycle(encycle(asList(Utils.createIntArray1D(1, 115, 1)), 51)).val);
	} 
	
	private ListNode encycle(ListNode n, int to) {
		Map<Integer, ListNode> val2Node = new HashMap<Integer, ListNode>();
		ListNode first = n;
		ListNode prev = n;
		n = n.next;
		while(n != null){
			val2Node.put(n.val, n);
			prev = n;
			n = n.next;
		}
		prev.next = val2Node.get(to);
		return first;
	}
	
	private ListNode encycle(ListNode n) {
		ListNode first = n;
		ListNode prev = n;
		n = n.next;
		while(n != null){
			prev = n;
			n = n.next;
		}
		
		prev.next = first;
		return first;
	}
}
